package com.tianze.tzkf.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayCallBack;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.ZolozAuthenticationCustomerSmilepayInitializeRequest;
import com.alipay.api.response.ZolozAuthenticationCustomerSmilepayInitializeResponse;
import com.alipay.iot.sdk.APIManager;
import com.alipay.iot.sdk.device.DeviceAPI;
import com.alipay.iot.sdk.payment.PaymentAPI;
import com.alipay.zoloz.smile2pay.service.Zoloz;
import com.google.gson.Gson;
import com.seedien.cardreader.idvender.BaseIDCardLib;
import com.seedien.cardreader.util.IdCardUtil;
import com.tencent.wxpayface.IWxPayfaceCallback;
import com.tencent.wxpayface.WxPayFace;
import com.tencent.wxpayface.WxfacePayCommonCode;
import com.tianze.tzkf.BannerActivity;
import com.tianze.tzkf.MainActivity;
import com.tianze.tzkf.app.App;
import com.tianze.tzkf.bean.GetSmilePayMsgBean;
import com.tianze.tzkf.bean.GetWxpayFaceAutoInfoBean;
import com.tianze.tzkf.bean.LoginClientIdBean;
import com.tianze.tzkf.bean.LogoOutMsgBean;
import com.tianze.tzkf.bean.PayingWithFaceReplyBean;
import com.tianze.tzkf.bean.SimleFaceReplyBean;
import com.tianze.tzkf.bean.SmileAuthTokenBean;
import com.tianze.tzkf.bean.SocketState;
import com.tianze.tzkf.bean.Token;
import com.tianze.tzkf.bean.WecatReturnData;
import com.tianze.tzkf.common.ActivityManager;
import com.tianze.tzkf.net.RetrofitFactory;
import com.tianze.tzkf.utils.Alipay_respon;
import com.tianze.tzkf.utils.ApkInfoUtil;
import com.tianze.tzkf.utils.CheckWifi;
import com.tianze.tzkf.utils.LogUtil;
import com.tianze.tzkf.utils.NetEvent;
import com.tianze.tzkf.utils.SSLSocketFactoryUtil;
import com.tianze.tzkf.utils.ToastUtils;
import com.tianze.tzkf.utils.statusbar.StatusBarCompat;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import static android.provider.Settings.ACTION_WIFI_SETTINGS;

/**
 * Created by Zcyang on 2018/1/22.
 */

public abstract class BaseActivity extends AppCompatActivity implements NetEvent , BaseIDCardLib.CardReadCallback{


    private boolean isNetChanges;
    private int netMobile;
    private String wXInit = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //        overridePendingTransition(0,0);//关闭activity启动动画
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        zoloz = Zoloz.getInstance(getApplicationContext());

        Map<String, String> m1 = new HashMap<>();
        try {


        WxPayFace.getInstance().initWxpayface(this, m1, new IWxPayfaceCallback() {
            @Override
            public void response(Map info) throws RemoteException {
                if ( info != null) {
                    String code = (String)info.get(WecatReturnData.RETURN_CODE);
                    String msg = (String)info.get(WecatReturnData.RETURN_MSG);

                    if (code.equals("SUCCESS") && code != null){
//                        rawData(getSmilePayMsgBean);
                        wXInit = "SUCCESS";
                        return;
                    }else {
                        wXInit = "";
                        Log.e("Wecat刷脸SDK初始化 : ","微信SDK初始化失败:"+msg);
                        Toast.makeText(BaseActivity.this,"微信SDK初始化失败",Toast.LENGTH_LONG).show();
                    }

                }else {
                    wXInit = "";
                    Log.e("Wecat刷脸SDK初始化 : ","返回值为空：微信SDK初始化失败");
                    Toast.makeText(BaseActivity.this,"微信SDK初始化失败",Toast.LENGTH_LONG).show();
                }

            }
        });

        }catch (Exception e){

        }

        IdCardUtil.getInstance().regist(this, this);
        //设置所有activity不可旋转,防止快速点击APP消失
        //        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // 隐藏顶部的状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(getLayoutId());
        ButterKnife.bind(this);

        setOverflowShowingAlways();
        ActivityManager.getInstance().add(this);
        ActivityManager.getInstance().checkActivityNum();


        initTitle();

        initData();
        StatusBarCompat.translucentStatusBar(BaseActivity.this, true);


    }


    @Override
    protected void onResume() {
        super.onResume();
        if (CheckWifi.checkWifi() == false) {
            //当前无网络
            show_dialog("您的网络异常，请重连网络");
            alertDialog_show();
            Log.e("当前无网络",">>>>>>>>>>");
        }else {
            reflshData();

            initSockect();
        }
    }

    private void setOverflowShowingAlways() {
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *
     */
    protected abstract void initData();

    protected abstract void reflshData();

    /**
     * 初始化标题
     */
    protected abstract void initTitle();

    /**
     * 绑定布局
     *
     * @return 布局ID
     */
    protected abstract int getLayoutId();


    /**
     * 跳转Activity
     *
     * @param Activity 要跳转到的Activity
     * @param bundle   携带的数据
     */
    public void goToActivity(Class Activity, Bundle bundle) {
        Intent intent = new Intent(this, Activity);
        if (bundle != null && bundle.size() != 0) {
            intent.putExtra("data", bundle);
        }
        startActivity(intent);
    }


    /**
     * 关闭当前Activity
     */
    public void removeCurrentActivity() {
//        if (ActivityManager.getInstance() != null) {
//            ActivityManager.getInstance().removeCurrent();
//        }

        if (ActivityManager.getInstance() != null) {
            ActivityManager.getInstance().finishActivity(this);
        }


    }

    @Override
    public void finish() {
        super.finish();
        //        overridePendingTransition(0,0);//关闭activity开启动画

    }

    /**
     * 移除所有页面
     */
    public void removeAllActivity() {
        if (ActivityManager.getInstance() != null) {
            ActivityManager.getInstance().finishAllActivity();
        }
    }

    /**
     * 获取当前时间
     *
     * @return 当前时间戳
     */
    public String getCurrentTime() {
        long time = System.currentTimeMillis();
        String time_stamp = String.valueOf(time);
        return time_stamp;
    }


    public void saveIsFirst(Context context, String key, boolean value) {
        SharedPreferences sp = context.getSharedPreferences("pj_is_first", Context.MODE_PRIVATE);
        sp.edit().putBoolean(key, value).commit();
    }


    public boolean readIsFirst(Context context, String key) {

        SharedPreferences sp = context.getSharedPreferences("pj_is_first", Context.MODE_PRIVATE);

        return sp.getBoolean(key, true);
    }

    /**
     * 保存登录token,手势密码,以及指纹
     */
    public void saveToken(Token.DataBean token) {
        SharedPreferences sp = App.getAppContext().getSharedPreferences("token_info", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("token", token.getToken());
        editor.commit();
    }

    /**
     * 获取用户token
     *
     * @return 返回token类
     */
    public Token.DataBean readToken() {
        SharedPreferences sp = App.getAppContext().getSharedPreferences("token_info", Context.MODE_PRIVATE);
        Token.DataBean token = new Token.DataBean();
        token.setToken(sp.getString("token", ""));
        return token;
    }

    /**
     * 保存登录token,手势密码,以及指纹
     */
    public void saveUser(String username) {
        SharedPreferences sp = App.getAppContext().getSharedPreferences("user_info", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("username", username);
        editor.commit();
    }

    /**
     * 获取用户token
     *
     * @return 返回token类
     */
    public String readUser() {
        SharedPreferences sp = App.getAppContext().getSharedPreferences("user_info", Context.MODE_PRIVATE);
        String username = sp.getString("username", "");
        return username;
    }


    /**
     * 去登陆
     *
     * @param msg        是否登录信息
     * @param isBackMain 是否返回首页
     */
    public void judgeLogin(String msg, boolean isBackMain) {
        if (msg.equals("您尚未登录")) {
            ToastUtils.showToast(this, "您尚未登录,请先登录");
            Bundle bundle = new Bundle();
            bundle.putBoolean("isBackMain", isBackMain);
            //            goToActivity(LoginOrRegisterActivity.class, bundle);
            clearUserInfo();
        }
    }

    /**
     * 清除用户登录信息
     */
    public void clearUserInfo() {
        dologout();
    }

    /**
     * 清除SP
     */
    public void dologout() {
        SharedPreferences sp_user = this.getSharedPreferences("user_info", Context.MODE_PRIVATE);
        SharedPreferences sp_token = this.getSharedPreferences("token_info", Context.MODE_PRIVATE);
        sp_user.edit().clear().commit();
        sp_token.edit().clear().commit();


    }


    @Override
    public void onNetChange(int netMobile) {
        this.netMobile = netMobile;
        switch (netMobile) {
            case 1://wifi
                isNetChanges = true;
                LogUtil.i("当前网络类型:wifi");
                break;
            case 0://移动数据
                isNetChanges = true;
                LogUtil.i("当前网络类型:移动数据");
                break;
            case -1://没有网络
                isNetChanges = false;
                LogUtil.i("当前网络类型:没有网络");
                break;
        }
        isNetConnect(isNetChanges);
    }

    protected abstract void isNetConnect(boolean isNetChanges);

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebSocketClient != null){
            Log.e(TAG, "onDestroy: " + "1111111111111");
            mWebSocketClient.close();
        }
//        IdCardUtil.getInstance().unregist();
        close_Icard();
        Log.e(TAG, "onDestroy: " + ">>>>>>>>>>>>>");

    }


    //通过反射获取ro.serialno
    public static String getSerialNumber() {

        String serial = null;

        try {

            Class<?> c = Class.forName("android.os.SystemProperties");

            Method get = c.getMethod("get", String.class);

            serial = (String) get.invoke(c, "ro.serialno");

        } catch (Exception e) {

            e.printStackTrace();

        }

        return serial;

    }


    /*****************************************************************************/
    private Zoloz zoloz;
    public static final String KEY_INIT_RESP_NAME = "zim.init.resp";
    private static String TAG = BaseActivity.class.toString();
    private String address = "wss://online02.tiaze.com:8282";
    private URI uri;
    private WebSocketClient mWebSocketClient;
    private String token;
    private SmileAuthTokenBean.DataBeanX.DataBean SmileAuthTokenBean_data;
    private Map mockInfo;


    @SuppressLint("HandlerLeak")
    private Handler handlers = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 6:
                    LoginClientIdBean loginClientIdBean = (LoginClientIdBean) msg.obj;
                    setDeviceOnLine(loginClientIdBean);
                    break;
                case 7:
                    Log.e("handle接收重连",".............");
                    SocketState socketState_handle = (SocketState) msg.obj;


                    if (socketState_handle.isB() == true){ // 断网

                        if (alertDialog  == null){
                            show_dialog("您的网络异常，请重连网络");
                            alertDialog_show();
                        }

                        if (socketState_handle.getI() == 1006){
                            if (mWebSocketClient != null) {
                                mWebSocketClient.close();
                                Log.e("handle接收重连",".....断网，开始重连........");
                            }
                            mWebSocketClient = null;
                            initSockect();
                        }

                    }else { // 销毁，或重连

                        if (socketState_handle.getI() == 1000){
                            //销毁
                        }else if (socketState_handle.getI() == -1){
                            if (mWebSocketClient != null) {
                                mWebSocketClient.close();
                                Log.e("handle接收重连",".....重新连接连接不上........");
                            }
                            mWebSocketClient = null;
                            initSockect();
                        }

                    }



                    break;
                case 8:
                    GetSmilePayMsgBean getSmilePayMsgBean = (GetSmilePayMsgBean) msg.obj;
                    smilePayInit(getSmilePayMsgBean);
                    //startSmilePay(getSmilePayMsgBean);

                    break;

                case 9:
                    LogoOutMsgBean logoOutMsgBean = (LogoOutMsgBean) msg.obj;
                    Log.e("此账号另一台设备上线terminal",".............");
                    //退出登录
                    if (mWebSocketClient != null) {
                        mWebSocketClient.close();
                    }
                    mWebSocketClient = null;
                    show_loginOutDialog("账号另一台设备上登录");
                    break;

                case 10:
                    Toast.makeText(BaseActivity.this,"刷脸失败",Toast.LENGTH_SHORT).show();
                    break;




            }


        }
    };


    public void initSockect() {
        try {
            uri = new URI(address);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        if (mWebSocketClient == null) {

            mWebSocketClient = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    Log.e(TAG, "Socket_onOpen: ");
                    if (alertDialog != null) {
                        alertDialog.dismiss();
                        alertDialog = null;
                    }
                }

                @Override
                public void onMessage(String s) {
                    Log.e(TAG, "onMessage: " + s);
                    Gson gson = new Gson();
                    LoginClientIdBean loginClientIdBean = gson.fromJson(s, LoginClientIdBean.class);
                    if (TextUtils.equals("login", loginClientIdBean.getType())) {
                        Log.e("WebSocket","msg:login");
                        Message msg = Message.obtain();
                        msg.obj = loginClientIdBean;
                        msg.what = 6;
                        handlers.sendMessage(msg);
                        // mHandler.sendMessageDelayed(msg,3000);
                        return;
                    }
                    GetSmilePayMsgBean getSmilePayMsgBean = gson.fromJson(s, GetSmilePayMsgBean.class);
                    if (TextUtils.equals("smile", getSmilePayMsgBean.getMsg().getType()) && TextUtils.equals("pay", getSmilePayMsgBean.getMsg().getPay_type())) {
                        Log.e("WebSocket","msg:pay");
                        Message msg = Message.obtain();
                        msg.obj = getSmilePayMsgBean; 
                        msg.what = 8;
                        handlers.sendMessage(msg);
                        return;

                    }

                    if (TextUtils.equals("smile", getSmilePayMsgBean.getMsg().getType()) && TextUtils.equals("fundauth", getSmilePayMsgBean.getMsg().getPay_type())) {
                        Log.e("WebSocket","msg:fundauth");
                        Message msg = Message.obtain();
                        msg.obj = getSmilePayMsgBean;
                        msg.what = 8;
                        handlers.sendMessage(msg);
                        return;
                    }
                    LogoOutMsgBean logoOutMsgBean = gson.fromJson(s, LogoOutMsgBean.class);

                    if (TextUtils.equals("smile", logoOutMsgBean.getMsg().getType())&& TextUtils.equals("logout", logoOutMsgBean.getMsg().getPay_type())){
                        Log.e("WebSocket","msg:logout");
                        Message msg = Message.obtain();
                        msg.obj = logoOutMsgBean;
                        msg.what = 9;
                        handlers.sendMessage(msg);
                        return;
                    }

                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    Log.e("Socket_onClose","i:"+i+",b:"+b);
                    SocketState socketState = new SocketState();
                    socketState.setI(i);
                    socketState.setB(b);

                    Message msg = Message.obtain();
                    msg.obj = socketState;
                    msg.what = 7;
                    handlers.sendMessageDelayed(msg, 3000);
                }

                @Override
                public void onError(Exception e) {
                    Log.e(TAG, "Socket_onError: "+e.getMessage());
//                    Message msg = Message.obtain();
//                    msg.what = 7;
//                    handler.sendMessageDelayed(msg, 3000);
                }
            };


            //方案一  https://blog.csdn.net/nerv2013/article/details/80620295
//            try {
//                mWebSocketClient.setSocket(SSLSocketFactoryUtil.creatSSLSocketFactory().createSocket(uri.getHost(),uri.getPort()));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }

            //方案二  https://www.cnblogs.com/wcAndroid/p/7723403.html
         //   mWebSocketClient.setSocket(SSLSocketFactoryUtil.creatSSLSocketFactory().createSocket());

            //方案三 自定义证书  https://blog.csdn.net/qq_34161388/article/details/75712014
            //   mWebSocketClient.setSocket(SSLSocketFactoryUtil.creatSSLSocketFactory().createSocket());

            mWebSocketClient.connect();
        }
    }


    private void setDeviceOnLine(LoginClientIdBean loginClientIdBean) {

        Map<String, String> request = new HashMap<>();
        request.put("type", loginClientIdBean.getType());
        request.put("login_type", "2");
        request.put("client_id", loginClientIdBean.getClient_id());
        //  request.put("user_phone", getSerialNumber());

        String serialNumber = getSerialNumber();
        if (serialNumber != null && !serialNumber.equals("")) {
            request.put("user_phone", serialNumber);
            Log.e("getSerialNumber", ">>" + serialNumber);
        } else {
            serialNumber = ApkInfoUtil.getANDROID_ID(this);
            Log.e("getANDROID_ID", ">>" + serialNumber);
            request.put("user_phone", serialNumber);
        }

        Observable<Token> setDeviceOnLine = RetrofitFactory.getInstance(TAG).setDeviceOnLine(request);
        setDeviceOnLine.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Token>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Token token) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    /**
     *   接收WebSocket刷脸的前期准备例如初始化SDK（微信、支付宝）
     */
    private void smilePayInit(final GetSmilePayMsgBean getSmilePayMsgBean){

        if (getSmilePayMsgBean.getMsg().getPayways().equals("weixin")){
            initWxPay(getSmilePayMsgBean);
        }else if (getSmilePayMsgBean.getMsg().getPayways().equals("alipay")){
            startSmilePay(getSmilePayMsgBean);
        }

    }


    /**
     *  1 . 初始化微信刷脸支付SDK
     */
    public void initWxPay(GetSmilePayMsgBean getSmilePayMsgBean){

        if (wXInit.equals("SUCCESS")){
            rawData(getSmilePayMsgBean);
        }


    }

    /**
     *  2. 获取微信人脸验证信息
     */
    public void rawData(GetSmilePayMsgBean getSmilePayMsgBean){
        Log.e("Wecat刷脸 : ","获取微信人脸验证信息:");
        WxPayFace.getInstance().getWxpayfaceRawdata(new IWxPayfaceCallback() {
            @Override
            public void response(Map info) throws RemoteException {
                if (info == null) {
                    Toast.makeText(BaseActivity.this,"微信刷脸调用失败",Toast.LENGTH_LONG).show();
                    return;
                }
                String rawdata = info.get("rawdata").toString();
                getWxpayFaceAuthInfo(rawdata,getSmilePayMsgBean);
            }
        });
    }

    /**
     *  3.  获取SDK调用凭证
     */
    String authinfo ;
    private void getWxpayFaceAuthInfo(String rawdata,GetSmilePayMsgBean getSmilePayMsgBean) {
        Log.e("开始调用Wecat刷脸获取SDK调用凭证","....");
        token = readToken().getToken();
        Map<String, String> request = new HashMap<>();
        request.put("token", token);
        request.put("rawdata", rawdata);
        String serialNumber = BannerActivity.getSerialNumber();
        if (serialNumber != null && !serialNumber.equals("")) {
            request.put("terminal", serialNumber);
            Log.e("getSerialNumber", ">>" + serialNumber);
        } else {
            serialNumber = ApkInfoUtil.getANDROID_ID(this);
            Log.e("getANDROID_ID", ">>" + serialNumber);
            request.put("terminal", serialNumber);
        }
        request.put("device_id", serialNumber);

        Observable<GetWxpayFaceAutoInfoBean> getWxpayFaceAuthInfo = RetrofitFactory.getInstance(TAG).getWxpayFaceAuthInfo(request);

        getWxpayFaceAuthInfo.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GetWxpayFaceAutoInfoBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(GetWxpayFaceAutoInfoBean getWxpayFaceAutoInfoBean) {
                        if (getWxpayFaceAutoInfoBean == null) {
                            Log.e("获取SDK调用凭证:返回值为空","....");
                            return;
                        }
                        if (getWxpayFaceAutoInfoBean.getCode().equals("10001")) {
                            authinfo = getWxpayFaceAutoInfoBean.getData().getData().getAuthinfo();
                            startSmilePay(getSmilePayMsgBean);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("刷脸收款失败onError",">>>>>>");
                    }

                    @Override
                    public void onComplete() {
                        Log.e("刷脸收款onComplete",">>>>>>");
                    }
                });
    }


    private void startSmilePay(final GetSmilePayMsgBean getSmilePayMsgBean) {

        Log.e("startSmilePay",">>>>>>>>>>>>");
        token = readToken().getToken();
        Map<String, String> request = new HashMap<>();
        request.put("token", token);
        request.put("payways", getSmilePayMsgBean.getMsg().getPayways());

        Observable<SmileAuthTokenBean> smileAuthToken = RetrofitFactory.getInstance(TAG).getSmileAuthToken(request);
        smileAuthToken.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SmileAuthTokenBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(SmileAuthTokenBean smileAuthTokenBean) {
                        if (smileAuthTokenBean.getCode() == 10001) {

                            ToastUtils.showToast(BaseActivity.this, "调用刷脸SDK");

                            SmileAuthTokenBean_data = smileAuthTokenBean.getData().getData();
                            mockInfo = mockInfo();

                            if (getSmilePayMsgBean.getMsg().getPayways().equals("weixin")){
                                startWecatFace(getSmilePayMsgBean);
                            }else if (getSmilePayMsgBean.getMsg().getPayways().equals("alipay")){
                                zoloz.zolozGetMetaInfo(mockInfo, smileToPayResponse -> {
                                    if (smileToPayResponse == null) {
                                        Log.e(TAG, "response is null");
                                        promptText(Alipay_respon.TXT_OTHER);
                                        return;
                                    }
                                    String code = (String)smileToPayResponse.get("code");
                                    String metaInfo = (String)smileToPayResponse.get("metainfo");


                                    //获取metainfo成功
                                    if (Alipay_respon.CODE_SUCCESS.equalsIgnoreCase(code) && metaInfo != null) {
                                        // Log.i(TAG, "metanfo is:" + metaInfo);

                                        //正式接入请上传metaInfo到服务端，不要忘记UrlEncode，使用服务端使用的sdk从服务端访问openapi获取zimId和zimInitClientData；
                                        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                                                SmileAuthTokenBean_data.getAppId(),
//                                            "2017031806275797",
                                                SmileAuthTokenBean_data.getRsaPrivateKey(),
//                                                "MIIEowIBAAKCAQEA6AqmRzgltnCQi9nmFP6fHcnQKdbdh2NY03fhTXyXoiWqawFFqpYtnTNJk+1es8h9UhMJ8xNqUdAvNV+fjNSn/C2Iv0TuEVAv/oNfiIev5r4K+KDvT/KqCnv1+lbC4/ILkWEUwalbwSiPcXAHCNI6rsd8LAlodK2MmwzfL+q1R83tqqXV5VMc5QPEHZV09rnBVd26AfcX9mAabwDA0/nBmvhd1dMoVFBvjv8fM7DgQ9RMX4weSC4Sg6u2y9F8+uF8+nu+LxLPXzTyZdmH8ROHreoRnUMxDWZCF0QSbsemhZSCW+cYBcidTehdmfZ4sczIig3iumrW/3DabZWClPVkfwIDAQABAoIBAFZEZ09BC5xJOyQTTZvukd90QUTc0h1cjRCJmCTDtmgdEr+XiHwEO08fWzJ45GV4m0bhNyi8xiFGgdaZB2tHQHDbyOQ7Tzr2kfFQjDrpHzds3g1TX8VcVWVycp+wk+JFAZH6AsqBGVC1sKae3K6l4hVKqtqAYOpH/2dBoNRisSTRMEvFgqyrmiNHIuOCRVQRp6WAEQfkmlJ+QBfRry8VYWE2WSXpLryLmM7UfPTJTDdGugP6yenP1tVB2EBsMo9VvbzkdFtQPucpED0+Kxa4xdkuoY5JmgYGqyj6+7vR7WYAVoBZPxsJrdwmCxJoNrT7czluhIQ7qR373kSV0tsXWmkCgYEA+eBuU6lfV3LCeerhVnbFDChKLvhkHH7pG/HxQV1n90ZHyZpmqwx5rBE3UGuxhukJiwPUmE2NewZKoQ+MnMcygtjoXyXS5bHIJ6ZpgM90yzoWpub+NCiTgh818i/9Ov/iCvlkJJ0jBcSSpiZC6R0IHikAewDF0gS61qFftnzYqBMCgYEA7bpVHMck92sTclPZ4e9EEbMvTUynZRdc6O18hxf1rKHVhyX5zM9dFG6K3A8dpp2+D1fnqr8r5/iuSLj0ZLAfrv1mAqwxx15EOzMdMCweLbTebkkBwEiZibnE1/BkV+rMC5kbnxaPE6fujsvPHoO8JG2fDVDuZVITaGVxAmUFN2UCgYAM6ulJMexX3ProypeznJg7NKoBG54xSu5KH4vVUTrasatsZKsCFLcFii5N3gNjchCoOx52cSvrPDwHb4JZaILX+NaqdI4eib5LLnMt0Yu8Jdid8Dsb/y0BARQM3SY+MpRA9PuUWPtChRL/u+KhonqU9JGtyjBv1wbBqb4E9RdOOQKBgQCNOKffFJ5tLHq86/r/MLfrG9r5vJOkhiB3br0PM7iJ+Qlz46dld7n/rTtoRsKCfCqvyrSgxjg68Yv3P4hPWCE6PuYeqFRZ7zHxSQgJ2euDk3KfaVdU9sve+TBqZy/02lKkgSvbcfdE4fnhckl0AyX9LfHSY0V7gypsVfawSXqz0QKBgGsv8cR2cpqReCHQbRygbGRWsVNWl4hlznVMoDzSPb3SFD02iMheYf4hWBjuvy5+jLjWumlWr+LvfQoRJfhkAbfIrlq9o8oIxT4ehk/XQ4RPZ7j2xAqtVcR/f4Dax4tdHEMGB2rjWwPPpaoEfU1PVyW9TaHoD/5rhCt6y/UEuJdC\n",
                                                "json",
                                                "utf-8",
                                                null,
                                                "RSA2");

//                                    ZolozAuthenticationCustomerSmilepayInitializeRequest
                                        ZolozAuthenticationCustomerSmilepayInitializeRequest request1
                                                = new ZolozAuthenticationCustomerSmilepayInitializeRequest();

                                        // zolozGetMetaInfo接口返回的metainfo对象中加入业务参数
                                        JSONObject zimmetainfo = JSON.parseObject(metaInfo);
                                        JSONObject merchantInfo = zimmetainfo.getJSONObject("merchantInfo");
                                        merchantInfo.put("pay_amount", getSmilePayMsgBean.getMsg().getPay_amount());//可选，支付币种订单金额,值为double类型
                                        merchantInfo.put("pay_currency", "CNY");//可选，支付币种，目前仅支持 人民币：CNY

                                        JSONObject extInfo = new JSONObject();

                                        /* start: 如果是姓名＋身份证号方式的刷脸支付，请加入以下代码 */
                                        extInfo.put("certNo", card_Id); //必填，当前被认证用户的身份证号
                                        extInfo.put("certName", card_Name);//必填，当前被认证用户的姓名（保持和身份证一致）
                                        extInfo.put("certType", "IDCARD"); //必填，写为IDCARD，表明身份证
                                        extInfo.put("bizType", "12"); //必填，固定写为8，表明基于姓名和身份证号的刷脸支付场景
                                        /* end: -------------------------------------------- */


                                        String app_auth_token = smileAuthTokenBean.getData().getData().getApp_auth_token();

                                        request1.putOtherTextParam("app_auth_token", app_auth_token);
                                        //如果有身份证信息就传extinfo
                                        if (!card_Id .equals("") && !card_Name.equals("")) {
                                            zimmetainfo.put("extInfo", extInfo);
                                        }
                                        request1.setBizContent(zimmetainfo.toJSONString());

                                   /* request1.setBizContent("{" +
                                            "    \"app_id\":\"2088031379002395\"" +
                                            "  }");*/


                                        //起一个异步线程发起网络请求
                                        alipayClient.execute(request1,
                                                new AlipayCallBack() {
                                                    @Override
                                                    public AlipayResponse onResponse(AlipayResponse response) {
                                                        if (response != null && Alipay_respon.SMILEPAY_CODE_SUCCESS.equals(response.getCode())) {
                                                            try {
                                                                ZolozAuthenticationCustomerSmilepayInitializeResponse zolozResponse
                                                                        = (ZolozAuthenticationCustomerSmilepayInitializeResponse)response;

                                                                String result = zolozResponse.getResult();
                                                                JSONObject resultJson = JSON.parseObject(result);
                                                                String zimId = resultJson.getString("zimId");
                                                                String zimInitClientData = resultJson.getString("zimInitClientData");
                                                                //人脸调用
                                                                smile(zimId, zimInitClientData,getSmilePayMsgBean);
                                                            } catch (Exception e) {
                                                                promptText(Alipay_respon.TXT_OTHER);
                                                            }
                                                        } else {
                                                            promptText(Alipay_respon.TXT_OTHER);
                                                            Log.e(TAG, "SMILEPAY_CODE_SUCCESS :" + Alipay_respon.SMILEPAY_CODE_SUCCESS);
                                                            Log.e(TAG, "Code :" + response.getCode());
                                                        }
                                                        return null;
                                                    }
                                                });
                                    } else {
                                        promptText(Alipay_respon.TXT_OTHER);

                                    }
                                });
                            }

                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }


    /**
     * 调起支付宝SDK刷脸
     * @param zimId 刷脸付token，从服务端获取，不要mock传入
     * @param protocal 刷脸付协议，从服务端获取，不要mock传入
     * @param getSmilePayMsgBean
     */
    private void smile(String zimId, String protocal, GetSmilePayMsgBean getSmilePayMsgBean) {

        Map params = new HashMap();
        params.put(KEY_INIT_RESP_NAME, protocal);
        zoloz.zolozVerify(zimId, params, smileToPayResponse -> {
            if (smileToPayResponse == null) {
                promptText(Alipay_respon.TXT_OTHER);
                return;
            }
            //ToastUtils.showToast(this,smileToPayResponse.toString());

            String code = (String)smileToPayResponse.get("code");
            String fToken = (String)smileToPayResponse.get("ftoken");
            String subCode = (String)smileToPayResponse.get("subCode");
            String msg = (String)smileToPayResponse.get("msg");
            // Log.d(TAG, "get_ftoken is:" + fToken);

            //刷脸成功
            if (Alipay_respon.CODE_SUCCESS.equalsIgnoreCase(code) && fToken != null) {
                //promptText("刷脸成功，返回ftoken为:" + fToken);
                //这里在Main线程，网络等耗时请求请放在异步线程中
                //后续这里可以发起支付请求
                //https://docs.open.alipay.com/api_1/alipay.trade.pay
                //需要修改两个参数
                //scene固定为security_code
                //auth_code为这里获取到的fToken值
                //支付一分钱，支付需要在服务端发起，这里只是模拟
                Log.e(TAG, "set_ftoken is:" + fToken);

                //人脸支付调用
                if (getSmilePayMsgBean.getMsg().getPay_type().equals("pay")){
                    Log.e("刷脸支付",">>>>>>>>");
                    Log.e(TAG, "set_ftoken is:" + fToken);
                    smilePay(getSmilePayMsgBean,fToken, token,"");
                }else if (getSmilePayMsgBean.getMsg().getPay_type().equals("fundauth")){
                    //人脸预付权调用
                    Log.e("刷脸预授权",">>>>>>>>");
                    alipay_Uni(getSmilePayMsgBean,fToken, token);
                }


            } else if (Alipay_respon.CODE_EXIT.equalsIgnoreCase(code)) {
                promptText(Alipay_respon.TXT_EXIT);
            } else if (Alipay_respon.CODE_TIMEOUT.equalsIgnoreCase(code)) {
                promptText(Alipay_respon.TXT_TIMEOUT);
            } else if (Alipay_respon.CODE_OTHER_PAY.equalsIgnoreCase(code)) {
                promptText(Alipay_respon.TXT_OTHER_PAY);
            } else {
                String txt = Alipay_respon.TXT_OTHER;
                if (!TextUtils.isEmpty(subCode)) {
                    txt = txt + "(" + subCode + ")";
                }
                promptText(txt);
            }
        });
    }


    /**
     *  调起微信SDK刷脸
     */
    public void startWecatFace( GetSmilePayMsgBean getSmilePayMsgBean){
        HashMap params = new HashMap();
        params.put(WecatReturnData. PARAMS_FACE_AUTHTYPE, "FACEPAY");  // 刷脸方式
        params.put(WecatReturnData.PARAMS_APPID, SmileAuthTokenBean_data.getAppId()); // AppID 公众号
        params.put(WecatReturnData.PARAMS_MCH_ID, SmileAuthTokenBean_data.getMerchantId());        // 商户号
        params.put(WecatReturnData.PARAMS_STORE_ID, SmileAuthTokenBean_data.getStoreCode());           // 商户ID
        params.put(WecatReturnData.PARAMS_OUT_TRADE_NO,getSmilePayMsgBean.getMsg().getOut_trade_no() ); // 订单号

        //double dPayAmount =  Double.valueOf(getSmilePayMsgBean.getMsg().getPay_amount()) * 100;
        //int iPayAmount = (int) dPayAmount;
        params.put(WecatReturnData.PARAMS_TOTAL_FEE, getSmilePayMsgBean.getMsg().getPay_amount()); // 0.01元，以分为单位
        Log.e("微信的刷脸金额是：",getSmilePayMsgBean.getMsg().getPay_amount()+"");
        //params.put(WecatReturnData.PARAMS_TELEPHONE, phone);
        params.put(WecatReturnData.PARAMS_AUTHINFO, authinfo);

        Map<String , String> test_Map = new HashMap<>();


        WxPayFace.getInstance().getWxpayfaceCode(params, new IWxPayfaceCallback() {
            @Override
            public void response(Map info)  {

                if (info != null ){

                    String code = (String)info.get(WecatReturnData.RETURN_CODE);
                    switch (code){
                        case WxfacePayCommonCode.VAL_RSP_PARAMS_SUCCESS:
                            Log.e("微信刷脸：","刷脸完成");
                            String face_code = info.get("face_code").toString();
                            String openid = info.get("openid").toString();
                            //向后台请求支付
                            //人脸支付调用
                            if (getSmilePayMsgBean.getMsg().getPay_type().equals("pay")){
                                Log.e("刷脸支付",">>>>>>>>");
                                smilePay(getSmilePayMsgBean,face_code,token,openid);
                            }else if (getSmilePayMsgBean.getMsg().getPay_type().equals("fundauth")){
                                //人脸预付权调用
                                Log.e("刷脸预授权",">>>>>>>>");

                                smileFreeze(getSmilePayMsgBean, face_code, token, "", openid);
                            }


                            break;

                        case WxfacePayCommonCode.VAL_RSP_PARAMS_USER_CANCEL :
                            Log.e("微信刷脸：","用户取消");
                            break;

                        case WxfacePayCommonCode.VAL_RSP_PARAMS_SCAN_PAYMENT :
                            Log.e("微信刷脸：","扫码支付");
                            break;

                        case "ERROR" :
                            Log.e("微信刷脸：","发生错误");
                            break;
                    }

                }

            }
        });
    }





    private void smilePay(GetSmilePayMsgBean getSmilePayMsgBean, String ftoken, String token, String openid) {

        Map<String, String> request = new HashMap<>();
        String amount = getSmilePayMsgBean.getMsg().getPay_amount();

        Log.e("smilePay","刷脸");

        request.put("out_trade_no",getSmilePayMsgBean.getMsg().getOut_trade_no());
        request.put("token",token);
        request.put("port","pos");
        request.put("payways",getSmilePayMsgBean.getMsg().getPayways());
        request.put("amount", amount);
        request.put("remark","备注");

        if (getSmilePayMsgBean.getMsg().getPayways().equals("alipay")) {
            request.put("ftoken", ftoken);
            //初始化SDK
            APIManager apiManager = APIManager.getInstance();
            try {
                apiManager.initialize(getApplicationContext(), SmileAuthTokenBean_data.getPartnerId());
            } catch (APIManager.APIInitException e) {
                e.printStackTrace();
            }
            Log.e("DeviceAPI>>>", ">>>>>>>>>>>>" );
            PaymentAPI api = apiManager.getPaymentAPI();
            String terminal_params = api.signWithFaceToken(ftoken, amount);
            Log.e("terminal_params>>>", ">>>>>>>>>>>>"+terminal_params );
            request.put("terminal_params",terminal_params);
        }else if (getSmilePayMsgBean.getMsg().getPayways().equals("weixin")){
            request.put("ftoken", ftoken);
            request.put("openid", openid);
        }

        String terminal_id = getSerialNumber();
        if (terminal_id != null && !terminal_id.equals("")) {
            request.put("terminal_id",getSerialNumber());
        } else {
            terminal_id = ApkInfoUtil.getANDROID_ID(this);
            request.put("terminal_id",terminal_id);
        }





        Observable<PayingWithFaceReplyBean> smilePay = RetrofitFactory.getInstance(TAG).smilePay(request);

        smilePay.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PayingWithFaceReplyBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e("刷脸收款onSubscribe",">>>>>>");
                    }

                    @Override
                    public void onNext(PayingWithFaceReplyBean payingWithFaceReplyBean) {
                        if (payingWithFaceReplyBean == null) {
                            //  ToastUtils.showToast(BannerActivity.this,"payingWithFaceReply: " + payingWithFaceReplyBean);
                            Log.e("刷脸收款失败:返回值为空",payingWithFaceReplyBean+">>>>>>");
                            return;
                        }
                        if (payingWithFaceReplyBean.getCode().equals("10001")) {
                            String content = "刷脸收款成功  ¥" + amount + " " + getCurrentTime();
                            Log.e("刷脸收款成功",payingWithFaceReplyBean.getMsg()+">>>>>>");

                            /*model.startGt(ISharedPreference.getInstance(getApplication()).getCid(), "天择可付推送提醒", content, () -> {
                                BaiduSpeechClient.getInstance().speak("收款" + amount + "元");
                            });*/
//                            showPrintDialog(payingWithFaceReplyBean);
//                            print(payingWithFaceReplyBean);
                            ToastUtils.showToast(BaseActivity.this, "支付状态：" + payingWithFaceReplyBean.getMsg());
                        } else {
                            Log.e("刷脸收款失败 ：返回码不为10001",payingWithFaceReplyBean.getMsg()+">>>>");
                            Toast.makeText(BaseActivity.this,payingWithFaceReplyBean.getMsg(),Toast.LENGTH_LONG).show();
                            //  ToastUtils.showToast(BannerActivity.this, payingWithFaceReplyBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("刷脸收款失败onError",">>>>>>");
                    }

                    @Override
                    public void onComplete() {
                        Log.e("刷脸收款onComplete",">>>>>>");
                    }
                });


    }


    /**
     * mock数据，真实商户请填写真实信息.
     */
    private Map mockInfo() {
        Map merchantInfo = new HashMap();
        //以下信息请根据真实情况填写
        //商户 Pid
        merchantInfo.put("merchantId", SmileAuthTokenBean_data.getMerchantId());
//        merchantInfo.put("merchantId", "2088031379002395");
        //ISV PID
        merchantInfo.put("partnerId", SmileAuthTokenBean_data.getPartnerId());
//        merchantInfo.put("partnerId", "2088421609886161");
        //添加刷脸付功能的appid
        merchantInfo.put("appId", SmileAuthTokenBean_data.getAppId());
//        merchantInfo.put("appId", "2017031806275797");
        //机具编号，便于关联商家管理的机具
        String serialNumber = getSerialNumber();
        if (serialNumber != null && !serialNumber.equals("")) {
            merchantInfo.put("deviceNum", getSerialNumber());
        } else {
            serialNumber = ApkInfoUtil.getANDROID_ID(this);
            merchantInfo.put("deviceNum", serialNumber);
        }
        //商户的门店编号
        merchantInfo.put("storeCode", SmileAuthTokenBean_data.getStoreCode());
        //支付宝门店编号
        merchantInfo.put("alipayStoreCode", SmileAuthTokenBean_data.getStoreCode());
        //品牌编码
        merchantInfo.put("brandCode", SmileAuthTokenBean_data.getBrandCode());

        return merchantInfo;
    }


    /**
     * 获取刷脸预授权操作的初始化
     */
    public void alipay_Uni(GetSmilePayMsgBean getSmilePayMsgBean, String ftoken,String token){

        APIManager apiManager = APIManager.getInstance();
        try {
            apiManager.initialize(getApplicationContext(), SmileAuthTokenBean_data.getPartnerId());
        } catch (APIManager.APIInitException e) {
            e.printStackTrace();
        }

        PaymentAPI api = apiManager.getPaymentAPI();
        String amount = getSmilePayMsgBean.getMsg().getPay_amount();
        String terminal_params = api.signWithFaceToken(ftoken, amount);

        smileFreeze(getSmilePayMsgBean, ftoken, token, terminal_params , "");
    }

    /**
     * 刷脸预授权请求
     */
    private void smileFreeze(GetSmilePayMsgBean getSmilePayMsgBean, String ftoken, String token,String terminal_params,String openid) {

        Map<String, String> request = new HashMap<>();
        String price = getSmilePayMsgBean.getMsg().getPay_amount();

        request.put("token",token);
        request.put("remarks",getSmilePayMsgBean.getMsg().getRemark());
        request.put("price", price);
        request.put("out_trade_no",getSmilePayMsgBean.getMsg().getOut_trade_no());


        String terminal_id = getSerialNumber();
        if (terminal_id != null && !terminal_id.equals("")) {
            request.put("terminal_id",getSerialNumber());
        } else {
            terminal_id = ApkInfoUtil.getANDROID_ID(this);
            request.put("terminal_id",terminal_id);
        }



        if (getSmilePayMsgBean.getMsg().getPayways().equals("alipay")) {

            request.put("ftoken", ftoken);
            request.put("payways","alipay");
            request.put("terminal_params",terminal_params);

        }else if (getSmilePayMsgBean.getMsg().getPayways().equals("weixin")){

            request.put("ftoken", ftoken);
            request.put("payways","weixin");
            request.put("openid", openid);
        }


        Observable<SimleFaceReplyBean> smilePay = RetrofitFactory.getInstance(TAG).smileFreeze(request);

        smilePay.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SimleFaceReplyBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e("刷脸预授权onSubscribe",">>>>>>");
                    }

                    @Override
                    public void onNext(SimleFaceReplyBean simleFaceReplyBean) {
                        if (simleFaceReplyBean == null) {
                            //  ToastUtils.showToast(BannerActivity.this,"payingWithFaceReply: " + payingWithFaceReplyBean);
                            Log.e("刷脸预授权失败1",simleFaceReplyBean+">>>>>>");

                            return;
                        }
                        if (simleFaceReplyBean.getCode().equals("10001")) {
                            Log.e("刷脸预授权成功",simleFaceReplyBean.getMsg()+">>>>>>");

                            /*model.startGt(ISharedPreference.getInstance(getApplication()).getCid(), "天择可付推送提醒", content, () -> {
                                BaiduSpeechClient.getInstance().speak("收款" + amount + "元");
                            });*/
//                            showPrintDialog(payingWithFaceReplyBean);
//                            print(payingWithFaceReplyBean);
                            ToastUtils.showToast(BaseActivity.this, "支付状态：" + simleFaceReplyBean.getMsg());
                        } else {
                            Log.e("刷脸预授权失败",simleFaceReplyBean.getMsg()+">>>>");
                            //  ToastUtils.showToast(BannerActivity.this, payingWithFaceReplyBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("刷脸预授权失败onError",">>>>>>");
                    }

                    @Override
                    public void onComplete() {
                        Log.e("刷脸预授onComplete",">>>>>>");
                    }
                });


    }

    /**
     * 发起刷脸支付请求.
     * @param txt toast文案
     */
    void promptText(final String txt) {
        runOnUiThread(() -> Toast.makeText(getApplicationContext(), txt, Toast.LENGTH_LONG).show());
    }



    /**
     * 另一台设备上线，此设备北挤下线的对话框
     */
    AlertDialog loginOutDialog;
    public void show_loginOutDialog(String dialog_str) {
        Activity activity2 = ActivityManager.getInstance().currentActivity();
        AlertDialog.Builder builder = new AlertDialog.Builder(activity2);
        builder.setTitle("提示:");
        builder.setMessage(dialog_str);
        builder.setCancelable(false);
        builder.setPositiveButton("退出登录", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                loginOutDialog.dismiss();
                BaseActivity activity = (BaseActivity) BaseActivity.this;
                activity.clearUserInfo();
                activity.goToActivity(MainActivity.class,null);
                close_Icard();
                removeCurrentActivity();
                ToastUtils.showToast(BaseActivity.this,"已退出登录");
            }
        });
        loginOutDialog = builder.create();
        loginOutDialog.show();
    }


    /**
     * 无网络的对话框
     */
    AlertDialog alertDialog;
    public void show_dialog(String dialog_str) {
        Activity activity = ActivityManager.getInstance().currentActivity();
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("提示:");
        builder.setMessage(dialog_str);
        builder.setCancelable(false);
        builder.setPositiveButton("刷新网络", null);
        builder.setNegativeButton("去连接网络", null);
        alertDialog = builder.create();


        alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                Button positionButton=alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
                Button negativeButton=alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
                positionButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (CheckWifi.checkWifi() == true){
                            Toast.makeText(BaseActivity.this,"网络已经连接",Toast.LENGTH_SHORT).show();
                            if (alertDialog != null) {
                                alertDialog.dismiss();
                                alertDialog = null;
                            }
                           reflshData();

                        }else {
                            Toast.makeText(BaseActivity.this,"网络还未连接",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                negativeButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent_Internet = new Intent(ACTION_WIFI_SETTINGS);
                        startActivity(intent_Internet);

                    }
                });
            }
        });


    }

    public void alertDialog_show(){
       // alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        alertDialog.show();
    }


/**********************************************************/
    public void close_WebSocket(){

        if (mWebSocketClient != null) {
            Log.e("mWebSocketClient",":不为null");
            mWebSocketClient.close();
        }
       mWebSocketClient = null;
    }

    public void close_Icard(){
        Log.e("close_Icard","close_Icard....");
        IdCardUtil.getInstance().unregist();
    }





    //读卡器回调接口
    String card_Name = ""; // 身份证名称
    String card_Id = ""; // 身份证卡号
    @Override
    public void sendCardInfo(com.seedien.cardreader.instance.CardInfo cardInfo) {
        if (cardInfo != null) {
            if (cardInfo.getName() != null && !cardInfo.getName().equals("")) {
                card_Name = cardInfo.getName();
            }

            if (cardInfo.getId() != null && !cardInfo.getId().equals("")) {
                card_Id = cardInfo.getId();
            }
        }
    }


}
